package com.lagou.task18;

import java.util.concurrent.locks.ReentrantLock;

public class AccountRunnableTest implements Runnable{
    private int balance;
    private ReentrantLock lock = new ReentrantLock();
    public AccountRunnableTest(){

    }

    public AccountRunnableTest(int balance) {
        this.balance = balance;
    }

    public int getBalance() {
        return balance;
    }

    public void setBalance(int balance) {
        this.balance = balance;
    }

    @Override
    public /*synchronized*/ void run() {
        //synchronized是隐式锁，ReentrantLock是显示锁，ReentrantLock只能锁代码块
//        synchronized (this) {
            lock.lock();
            getMonney(200);
            lock.unlock();
//        }
    }
    //取款
    private void getMonney(int monney){
        int temp = getBalance();
        if (temp >= monney){
            System.out.println("正在出钞，请稍后。。。");
            temp -= monney;
            try {
                Thread.sleep(5000);
                setBalance(temp);
                System.out.println("剩余：" + getBalance());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else{
            System.out.println("余额不足！");
        }
    }

    public static void main(String[] args) {
        AccountRunnableTest ar1 = new AccountRunnableTest(1000);
        Thread t1 = new Thread(ar1);
        Thread t2 = new Thread(ar1);
        t1.start();
        t2.start();
        System.out.println("主线程等待子线程结束");
        try {
            t1.join();
            System.out.println("子线程1结束");
            t2.join();
            System.out.println("子线程2结束");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("账户余额" + ar1.getBalance());
    }

}
